from facegraph.django.middleware import FacebookGraphMiddleware
from django.utils import simplejson as json
from django.contrib import messages
from django.core.urlresolvers import reverse


class GraphMiddleware(FacebookGraphMiddleware):
    def access_token(self, request):
        try:
            return request.user.get_facebook_token()
        except AttributeError:
            return None


class AjaxMessaging(object):
    def process_response(self, request, response):
        if request.is_ajax() and response['Content-Type'] in ["application/javascript", "application/json"]:
            try:
                content = json.loads(response.content)
            except ValueError:
                return response

            django_messages = []

            for message in messages.get_messages(request):
                django_messages.append({
                    "message": message.message,
                    "message_pk": message.pk if message.is_persistent() else '',
                    "extra_tags": message.tags,
                    "close_timeout": message.close_timeout,
                    "link":
                        reverse('message_mark_closed', args=[message.pk])
                        if message.is_persistent() else '',
                })

            if request.user.is_authenticated():
                content['unclosed_notifications'] = request.user.get_notifications_count()

            content['django_messages'] = django_messages
            response.content = json.dumps(content)
        return response

